﻿package net.hainan.chat;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.RosterEntry;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Presence;

import com.scenery.R;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
/****
 *显示联系人列表
 * */
public class Openfire extends Activity implements OnMessageListener,
		OnContactStateListener, OnItemClickListener,OnClickListener
{
	public static XMPPConnection oConnection;
	public static Util oUtil;
	public static String oCurrentAccount;
	public static Map<String, Boolean> oChattingContactMap = new HashMap<String, Boolean>();
	private Roster oRoster;
	private ContactsAdapter oContactsAdapter;
	private ArrayList<RosterEntry> oEntries;
	private ListView olvContacts;
	private Thread oMessageReceiverThread;
	private Thread oUpdateContactStateThread;
	private MessageReceiver oMessageReceiver;
	private UpdateContactState oUpdateContactState;

	@Override
	protected void onDestroy()
	{
		super.onDestroy();
		oMessageReceiver.flag = false;
		oMessageReceiver.oCollector.cancel();
		oUpdateContactState.flag = false;
		Presence presence = new Presence(Presence.Type.unavailable);
		oConnection.sendPacket(presence);

		oConnection.disconnect();
		//oConnection = null;

		
	}
	public void contactStateChange()//设置联系人的状态
	{
		if (oConnection == null)
			return;
		
		Collection<RosterEntry> rosterEntries = oConnection.getRoster()
				.getEntries();//获得当前用户的所有联系人

		for (RosterEntry rosterEntry : rosterEntries)
		{
			
			Presence presence = oConnection.getRoster().getPresence(
					rosterEntry.getUser());//获得当前联系人的状态
			if (presence != null)//presence不在线为null
			{

				if (presence.isAvailable())
					
					oContactsAdapter.setContactIcon(rosterEntry.getUser(),
							R.drawable.online);//如果联系人在线，将图标资源ID换成online
				else
					
					oContactsAdapter.setContactIcon(rosterEntry.getUser(),
							R.drawable.offline);//如果联系人离线，将图标资源ID换成offline
			}

		}
	}

	public void processMessage(Message message)//处理联系人
	{

		String account = oUtil.getLeftString(message.getFrom(), "/");
		//是否第一次接到该联系人的聊天信息
		Boolean isChatting = oChattingContactMap.get(account);
		//是第一次接收到该联系人的聊天信息

		if (isChatting == null)
		{
			isChatting = false;
		}
		
		//设置标志，表示已不再是第一次接收联系人的聊天信息
		oChattingContactMap.put(account, true);
		//是第一次接收到该联系人的聊天信息
		if (!isChatting)
		{
			
			Intent intent = new Intent(this, ChatRoom.class);//显示聊天界面
			//向聊天界面传递账号和聊天消息
			intent.putExtra("contactAccount", account);
			intent.putExtra("msg", message.getBody());
			startActivity(intent);
		}

	}

	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id)
	{
		String account = oContactsAdapter.getAccount(position);
		Intent intent = new Intent(this, ChatRoom.class);
		intent.putExtra("contactAccount", account);
		startActivity(intent);

		oChattingContactMap.put(account, true);

	} 

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.openfire);
		Button btnzhuce = (Button) findViewById(R.id.btnzhuce);
		btnzhuce.setOnClickListener((OnClickListener) this);
		olvContacts = (ListView) findViewById(R.id.lvContacts);
		oEntries = new ArrayList<RosterEntry>();
		oRoster = oConnection.getRoster();//检索花名册
		oContactsAdapter = new ContactsAdapter(this);
		olvContacts.setOnItemClickListener(this);
		olvContacts.setAdapter(oContactsAdapter);

		oMessageReceiver = new MessageReceiver(oCurrentAccount);
		oMessageReceiver.setOnMessageListener(this);
		oMessageReceiverThread = new Thread(oMessageReceiver);
		oMessageReceiverThread.start();

		oUpdateContactState = new UpdateContactState();
		oUpdateContactState.setOnContactStateListener(this);
		oUpdateContactStateThread = new Thread(oUpdateContactState);
		oUpdateContactStateThread.start();

		setTitle("联系人列表(" + oCurrentAccount + ")");

	}
    
	public static class Contact//联系人的信息
	{
		public int iconResourceId;
		public String account;
		public String nickname;
	}

	private class ContactsAdapter extends BaseAdapter
	{
		private Context oContext;
		private LayoutInflater oLayoutInflater;
		private ArrayList<Contact> oContacts = new ArrayList<Contact>();
		private Map<String, Integer> oContactMap = new HashMap<String, Integer>();

		public ContactsAdapter(Context context)
		{
			oContext = context;
			oLayoutInflater = (LayoutInflater) context
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			//获得联系人列表
			loadContacts();
		}

		private void loadContacts()
		{
            //获得RosterEntry对象的集合，每一个RosterEntry对象表示一个联系人
			Collection<RosterEntry> entries = oRoster.getEntries();
			for (RosterEntry entry : entries)
			{
				Contact contact = new Contact();
				//设置联系人图标的资源ID（默认是离线状态）
				contact.iconResourceId = R.drawable.offline;
				//设置联系人的账号
				contact.account = entry.getUser();
				//设置联系人的昵称
				contact.nickname = oUtil.getLeftString(entry.getUser(), "@");
				oContacts.add(contact);
				oContactMap.put(contact.account, oContacts.size() - 1);

			}

		}
		

	
		public int getCount()
		{
			return oContacts.size();
		}

		public Object getItem(int position)
		{
			return oContacts.get(position);
		}

		public String getAccount(int position)
		{
			return oContacts.get(position).account;
		}

		public long getItemId(int position)
		{
			return position;
		}
        //设置联系人的图标ID。当联系人上线或离线时需要调用该方法来改变联系人前面的图标
		public void setContactIcon(String account, int resourceId)
		{
			Integer position = oContactMap.get(account);
			if (position != null)
			{
				//如果联系人图标资源ID已变化，则设置新的图标资源ID
				if (oContacts.get(position).iconResourceId != resourceId)
				{
					oContacts.get(position).iconResourceId = resourceId;
					notifyDataSetChanged();
				}
			}

		}

		public View getView(int position, View convertView, ViewGroup parent)
		{
			
			LinearLayout linearLayout = (LinearLayout) oLayoutInflater.inflate(
					R.layout.contact_item, null);
			ImageView ivContactIcon = (ImageView) linearLayout
					.findViewById(R.id.ivContactIcon);
			TextView tvContactNickname = ((TextView) linearLayout
					.findViewById(R.id.tvContactNickname));
			//设置联系人图标资源ID
			ivContactIcon
					.setImageResource(oContacts.get(position).iconResourceId);
			//设置联系人昵称
			tvContactNickname.setText(oContacts.get(position).nickname);
			return linearLayout;
		}
	}

	public void onClick(View v) {
		// TODO Auto-generated method stub
		Intent intent = new Intent(this,Register.class);//跳转页面
		startActivity(intent);
	}
}
